"""
任务业务逻辑模块
处理任务相关的业务逻辑
"""

import time
import threading

# 存储任务状态的字典
tasks = {}

def create_task():
    """创建新任务"""
    task_id = str(int(time.time()))
    tasks[task_id] = {
        "status": "running",
        "progress": 0,
        "message": "Task started"
    }
    return task_id

def get_task_status(task_id):
    """获取任务状态"""
    return tasks.get(task_id)

def delete_task(task_id):
    """删除任务"""
    if task_id in tasks:
        del tasks[task_id]
        return True
    return False

def run_task(task_id):
    """
    在后台线程中运行模拟任务
    参数:
        task_id (str): 任务唯一标识符
    """
    # 模拟一个耗时任务，从1%到100%
    for i in range(1, 101):
        # 模拟工作负载，每次休眠0.1秒
        time.sleep(0.1)

        # 检查任务是否仍存在于tasks字典中（未被删除）
        if task_id in tasks:
            # 更新任务进度和消息
            tasks[task_id]["progress"] = i
            tasks[task_id]["message"] = f"Processing... {i}%"

    # 任务完成后更新状态和消息
    if task_id in tasks:
        tasks[task_id]["status"] = "completed"
        tasks[task_id]["message"] = "Task completed successfully"
